import FlagImage from '@/components/FlagImage';
import TagTags from '@/components/TagTags';
import { ArrowRightOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm, Radio, Space, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import BatchChangeProductsForm from './components/BatchChangeProductsForm';
import Form from './components/Form';

// import * as utils from '@/utils/utils';

import * as c from '@/services/consts';
import * as api from '@/services/vpnGroup';
import { PageContainer } from '@ant-design/pro-components';

const VpnGroupTreeList: React.FC = () => {
  //const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [batchChangeProductsVisible, setBatchChangeProductsVisible] =
    useState<boolean>(false);

  const [current, setCurrent] = useState<API.VpnGroupModel | undefined>(
    undefined,
  );
  const [parent, setParent] = useState<API.VpnGroupModel | undefined>(
    undefined,
  );
  const [productId, setProductId] = useState<string | undefined>(undefined);

  const [selectIds, setSelectIds] = useState<any[]>([]);
  const [filterStatus, setFilterStatus] = useState<boolean | undefined>(
    undefined,
  );
  const [filterType, setFilterType] = useState<number | undefined>(undefined);

  const [filterMemberLevel, setFilterMemberLevel] = useState<
    number | undefined
  >(undefined);

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const {
    getProduct,
    getProductMenuItems,
    reloadVpnGroupTrees,
    // getAreaFilter,
    getGroupAreaFilterPolicyText,
    getGeoipIsp,
  } = useModel('useGlobalModel', (model) => ({
    getProduct: model.getProduct,
    getProductMenuItems: model.getProductMenuItems,
    reloadVpnGroupTrees: model.reloadVpnGroupTrees,
    // getAreaFilter: model.getAreaFilter,
    getGroupAreaFilterPolicyText: model.getGroupAreaFilterPolicyText,
    getGeoipIsp: model.getGeoipIsp,
  }));

  const productMenuItems = getProductMenuItems(true);

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const result = await api.list(params, sorter, filter);

    let rootKeys: string[] = [];
    if (result.success && result.data && result.data.length > 0) {
      result.data.forEach((item) => {
        rootKeys.push(item.id);
      });

      //setExpandedRowKeys(rootKeys);
    }

    return Promise.resolve(result);
  };

  const handleFormSubmit = async (record: API.VpnGroupModel) => {
    // console.log({
    //     ...current,
    //     ...record,
    //   });
    //   return;

    if (parent) {
      record.parentId = parent.id;
    }
    record.mutiLangs = record.mutiLangs ? record.mutiLangs : {};

    // console.log(record);

    if (!record.userLimit) {
      record.userLimit = undefined;
    }

    let result: API.Result;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setParent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();

      //更新缓存
      await reloadVpnGroupTrees();
    }
  };

  const handleBatchChangeProductsSubmit = async (productIds: number[]) => {
    let result: API.Result;
    result = await api.changeProducts({
      keys: selectIds,
      productIds: productIds,
    });
    if (result && result.success === true) {
      setBatchChangeProductsVisible(false);
      actionRef.current?.clearSelected?.();
      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();

      //更新缓存
      await reloadVpnGroupTrees();
    }
  };

  let columns: ProColumns<API.VpnGroupModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'status',
      sorter: true,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '产品',
      align: 'center',
      width: 100,
      dataIndex: 'productIdsText',
      sorter: true,
      renderText: (_, record) => {
        if (record.productIds) {
          let text = '';
          for (let i = 0; i < record.productIds.length; i++) {
            const product = getProduct(record.productIds[i]);
            if (product) {
              if (text != '') {
                text += '/';
              }
              text += product.name;
            }
          }

          return text;
        }
        return '';
      },
    },
    {
      title: '用户等级',
      align: 'center',
      dataIndex: 'memberLevel',
      sorter: true,
      width: 100,
      renderText: (val) => {
        return c.getMemberLevelText(val);
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: true,
      width: 250,
      render: (text, record) => {
        let title = `${text}`;
        return (
          <>
            <div>
              <FlagImage flagName={record.flag} />
              {record.display != true ? <Tag>{title}</Tag> : title}
              {record.type == c.VpnGroupType.Ghost.value ? (
                <Tag color="green">{c.getVpnGroupTypeText(record.type)}</Tag>
              ) : (
                ''
              )}
              {record.policy?.cheaterId == c.CheaterType.TcpCheaterCdn.value ? (
                <Tag color="blue">CDN</Tag>
              ) : (
                ''
              )}
              {/* {record.policy?.allowIspIds?.map((val)=><Tag color='orange'>{getGeoipIsp(val)?.name}</Tag>)} */}
            </div>
          </>
        );
      },
    },
    {
      title: '分组代码',
      width: 100,
      dataIndex: 'code',
      sorter: true,
      render: (_, record) => {
        return (
          <>
            {record.preBridgeGroups.length > 0 ? (
              <div>
                {record.preBridgeGroups?.map((val) => (
                  <Tag color="blue">{val.code}</Tag>
                ))}

                {/* <ArrowRightOutlined /> */}
              </div>
            ) : (
              ''
            )}
            <div>
              {record.preBridgeGroups.length > 0 ? <ArrowRightOutlined /> : ''}
              {record.code}
            </div>
          </>
        );
      },
    },
    {
      title: '标签',
      width: 160,
      dataIndex: 'tags',
      render: (_, record) => <TagTags values={record.tags} />,
    },
    {
      title: 'ISP运营商',
      width: 120,
      render: (_, record) => {
        if (!record.policy?.ispFilterPolicyIspList) {
          return <></>;
        }
        var lines = [];
        for (let item of record.policy.ispFilterPolicyIspList) {
          var name = getGeoipIsp(item)?.name;
          if (
            record.policy.ispFilterPolicy == c.IspFilterPolicy.Whitelist.value
          ) {
            lines.push(<Tag color="green">{name}</Tag>);
          } else {
            lines.push(<Tag color="orange">{name}</Tag>);
          }
        }
        return lines;
      },
    },
    {
      title: '类型',
      align: 'center',
      dataIndex: 'type',
      width: 80,
      sorter: true,
      renderText: (_, record) => {
        return c.getVpnGroupTypeText(record.type);
      },
    },
    {
      title: '支持协议',
      align: 'center',
      dataIndex: 'protocol',
      sorter: true,
      width: 100,
      renderText: (val) => {
        // return val ? <Tag color={val == 3 ? 'green' : val == 1 ? "blue" : val == 2 ? "purple" : ""}>{c.getObjectText(c.VpnGroupProtocols, val)}</Tag> : "";
        return val ? (
          <Tag color="blue">{c.getObjectText(c.VpnGroupProtocols, val)}</Tag>
        ) : (
          ''
        );
      },
    },
    {
      title: '分配方式',
      width: 120,
      align: 'center',
      dataIndex: 'allotMode',
      sorter: true,
      renderText: (_, record) => {
        let allotMode = c.getVpnGroupAllotModeText(record.allotMode);
        if (record.allotMode == c.VpnGroupAllotMode.FixedIp.value) {
          return `${allotMode}`;
        } else if (record.allotMode == c.VpnGroupAllotMode.FixedUser.value) {
          //return `${allotMode} : ${record.allotConfig.perIpUserCount}`;
          return `${allotMode}`;
        }
        return null;
      },
    },
    // {
    //   title: '子分组',
    //   align: 'center',
    //   dataIndex: 'children',
    //   width: 80,
    //   renderText: (_, record) => {
    //     if (record.children != null) {
    //       return record.children.length;
    //     }
    //     return '-';
    //   },
    // },
    {
      title: '平台',
      dataIndex: '',
      sorter: false,
      renderText: (_, record) => {
        return record.policy?.displayPlatforms?.join(',');
      },
    },
    {
      title: '渠道',
      dataIndex: '',
      sorter: false,
      renderText: (_, record) => {
        return record.policy?.displayChannels?.join(',');
      },
    },
    {
      title: '版本策略',
      // width: 200,
      sorter: false,
      // renderText: (_, record) => {
      //   if (
      //     record.policy != null &&
      //     record.policy.displayAppVerComparePolicy &&
      //     record.policy.displayAppVerComparePolicy != '' &&
      //     record.policy.displayAppVerComparePolicyAppVer > 0
      //   ) {
      //     return `${record.policy.displayAppVerComparePolicy}${record.policy.displayAppVerComparePolicyAppVer}`;
      //   }
      //   return null;
      // },
      render: (_, record) => {
        if (
          record.policy?.platformAppVerCompares == null ||
          record.policy?.platformAppVerCompares.length < 1
        ) {
          return <></>;
        }

        let lines = [];
        if (
          record.policy != null &&
          record.policy.displayAppVerComparePolicy &&
          record.policy.displayAppVerComparePolicy != '' &&
          record.policy.displayAppVerComparePolicyAppVer > 0
        ) {
          lines.push(
            <span>
              {record.policy.displayAppVerComparePolicy}
              {record.policy.displayAppVerComparePolicyAppVer}
              <br />
            </span>,
          );
        }
        if (record.policy?.platformAppVerCompares) {
          for (let item of record.policy.platformAppVerCompares) {
            if (item.compareMode && item.compareMode != '') {
              lines.push(
                <span>
                  {item.platform}&nbsp;{item.compareMode}
                  {item.appVer}
                  <br />
                </span>,
              );
            }
          }
        }

        return lines;
      },
    },
    {
      title: '地区策略',
      dataIndex: '',
      sorter: false,
      render: (_, record) => {
        let policy = getGroupAreaFilterPolicyText(record.policy);
        return policy ? (
          <Tag color={policy.indexOf('显示') == -1 ? '' : 'blue'}>{policy}</Tag>
        ) : (
          policy
        );
        //return getGroupAreaFilterPolicyText(record.policy);

        // let policy = record.policy;
        // if (
        //   policy &&
        //   policy.displayAreaFilterPolicy &&
        //   policy.displayAreaFilterPolicy != '' &&
        //   policy.displayAreaFilterPolicyAreaFilterIds &&
        //   policy.displayAreaFilterPolicyAreaFilterIds.length > 0
        // ) {
        //   let text = '';
        //   if (
        //     policy.displayAreaFilterPolicy ==
        //     c.GroupDisplayAreaFilterPolicy.Display.value
        //   ) {
        //     text = '显示';
        //   } else if (
        //     policy.displayAreaFilterPolicy ==
        //     c.GroupDisplayAreaFilterPolicy.Hidden.value
        //   ) {
        //     text = '隐藏';
        //   }

        //   let fullAreas = [];

        //   for (
        //     let i = 0;
        //     i < policy.displayAreaFilterPolicyAreaFilterIds.length;
        //     i++
        //   ) {
        //     let id = policy.displayAreaFilterPolicyAreaFilterIds[i];

        //     let areaFilter = getAreaFilter(id);

        //     //console.log('policy.areaFilter: ', areaFilter);

        //     if (areaFilter != null) {
        //       let areas =
        //         areaFilter.areaGroup == c.AreaGroup.Foreign.value
        //           ? areaFilter.areas
        //           : areaFilter.areaGroup;

        //       fullAreas.push(areas);
        //     }
        //   }

        //   if (fullAreas.length > 0) {
        //     return `${text}:[${fullAreas.join(',')}]`;
        //   }
        // }
        // return null;
      },
    },
    {
      title: '用户策略',
      dataIndex: '',
      sorter: false,
      render: (_, record) => {
        let ret = [];
        if (record.policy?.testGroupUser == true) {
          ret.push(
            <>
              <span style={{ color: '#ff4d4f' }}>测试组用户可见</span>
              <br />
            </>,
          );
        }

        if (
          record.policy?.displayUserRegistPolicy != null &&
          record.policy?.displayUserRegistPolicy != '' &&
          record.policy?.displayUserRegistDay > 0
        ) {
          ret.push(
            <>
              <span style={{ color: '#ff4d4f' }}>
                注册 {record.policy?.displayUserRegistDay} 天
                {c.getRegistCompareModeText(
                  record.policy.displayUserRegistPolicy,
                )}
                可见
              </span>
            </>,
          );
        }
        if (record.policy?.displayUsers?.length > 0) {
          if (
            record.policy?.displayUserPolicy ==
            c.GroupDisplayUserPolicy.Display.value
          ) {
            ret.push(
              <>
                <span>指定用户显示</span>
                <br />
              </>,
            );
          } else if (
            record.policy?.displayUserPolicy ==
            c.GroupDisplayUserPolicy.Hidden.value
          ) {
            ret.push(
              <>
                <span>指定用户隐藏</span>
                <br />
              </>,
            );
          }
        }

        return ret;
      },
    },
    {
      title: '服务器',
      width: 140,
      align: 'center',
      dataIndex: 'validServerCount',
      sorter: true,
      renderText: (_, record) => {
        // if (
        //   record.children &&
        //   record.children.length > 0 &&
        //   record.serverCount < 1
        // ) {
        //   return '-';
        // }

        if (record.validServerCount == 0) {
          return (
            <span style={{ color: '#ff4d4f' }}>
              {record.validServerCount}/{record.serverCount}
            </span>
          );
        }
        return `${record.validServerCount}/${record.serverCount}`;
      },
    },
    {
      title: '最大用户数',
      align: 'center',
      width: 110,
      dataIndex: 'userLimit',
      valueType: 'digit',
      sorter: true,
    },
    // {
    //   title: '最大带宽MB',
    //   align: 'center',
    //   width: 110,
    //   dataIndex: 'maxBandwidth',
    //   valueType: 'digit',
    //   sorter: true,
    // },
    {
      title: '切换IP',
      dataIndex: 'changeIp',
      align: 'center',
      width: 80,
      render: (_, record) => {
        return record.changeIp > 0 ? (
          <Tag color="blue">{record.changeIp} 分钟</Tag>
        ) : (
          ''
        );
      },
    },
    {
      title: '排序',
      width: 60,
      align: 'center',
      dataIndex: 'sort',
      sorter: true,
    },

    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 160,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('vpngroup_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
                setParent(undefined);
              }}
            >
              编辑
            </a>,
          );
        }
        if (hasRight('vpngroup_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        if (!record.parentId && hasRight('vpngroup_create')) {
          cmps.push(
            <a
              key="create"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(undefined);
                setParent(record);
              }}
            >
              新建子分组
            </a>,
          );
        }
        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        expandable={
          {
            // defaultExpandAllRows: true,
            // childrenColumnName: 'children',
            // expandRowByClick: true,
            //expandedRowKeys: expandedRowKeys,
          }
        }
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              setProductId(tabKey as string);
            },
          },
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];
          toolbarDoms.push(
            <Space>
              <b>状态</b>
              <Radio.Group defaultValue="a" buttonStyle="solid">
                <Radio.Button
                  value="a"
                  onClick={() => {
                    setFilterStatus(undefined);
                  }}
                >
                  全部
                </Radio.Button>
                <Radio.Button
                  value="b"
                  onClick={() => {
                    setFilterStatus(true);
                  }}
                >
                  启用
                </Radio.Button>
                <Radio.Button
                  value="c"
                  onClick={() => {
                    setFilterStatus(false);
                  }}
                >
                  禁用
                </Radio.Button>
              </Radio.Group>
            </Space>,
          );
          toolbarDoms.push(
            <Space>
              <b>类型</b>
              <Radio.Group defaultValue="" buttonStyle="solid">
                <Radio.Button
                  value=""
                  onClick={() => {
                    setFilterType(undefined);
                  }}
                >
                  全部
                </Radio.Button>
                {c.VpnGroupTypeOptions.map((item) => (
                  <Radio.Button
                    value={item.value}
                    onClick={() => {
                      setFilterType(item.value);
                    }}
                  >
                    {item.label}
                  </Radio.Button>
                ))}
                {/* <Radio.Button
                  value={c.VpnGroupType.Normal.value}
                  onClick={() => {
                    setFilterType(c.VpnGroupType.Normal.value);
                  }}
                >
                  {c.VpnGroupType.Normal.label}
                </Radio.Button>
                <Radio.Button
                  value={c.VpnGroupType.Ghost.value}
                  onClick={() => {
                    setFilterType(c.VpnGroupType.Ghost.value);
                  }}
                >
                  {c.VpnGroupType.Ghost.label}
                </Radio.Button>
                <Radio.Button
                  value={c.VpnGroupType.Private.value}
                  onClick={() => {
                    setFilterType(c.VpnGroupType.Private.value);
                  }}
                >
                  {c.VpnGroupType.Private.label}
                </Radio.Button>
                <Radio.Button
                  value={c.VpnGroupType.Stream.value}
                  onClick={() => {
                    setFilterType(c.VpnGroupType.Stream.value);
                  }}
                >
                  {c.VpnGroupType.Stream.label}
                </Radio.Button> */}
              </Radio.Group>
            </Space>,
          );
          toolbarDoms.push(
            <Space>
              <b>级别</b>
              <Radio.Group defaultValue="" buttonStyle="solid">
                <Radio.Button
                  value=""
                  onClick={() => {
                    setFilterMemberLevel(undefined);
                  }}
                >
                  全部
                </Radio.Button>
                {c.MemberLevelOptions.map((item) => (
                  <Radio.Button
                    value={item.value}
                    onClick={() => {
                      setFilterMemberLevel(item.value);
                    }}
                  >
                    {item.label}
                  </Radio.Button>
                ))}
                {/* <Radio.Button
                  value={c.MemberLevel.Trial.value}
                  onClick={() => {
                    setFilterMemberLevel(c.MemberLevel.Trial.value);
                  }}
                >
                  {c.MemberLevel.Trial.label}
                </Radio.Button>
                <Radio.Button
                  value={c.MemberLevel.Free.value}
                  onClick={() => {
                    setFilterMemberLevel(c.MemberLevel.Free.value);
                  }}
                >
                  {c.MemberLevel.Free.label}
                </Radio.Button>
                <Radio.Button
                  value={c.MemberLevel.VIP.value}
                  onClick={() => {
                    setFilterMemberLevel(c.MemberLevel.VIP.value);
                  }}
                >
                  {c.MemberLevel.VIP.label}
                </Radio.Button>
                <Radio.Button
                  value={c.MemberLevel.Internal.value}
                  onClick={() => {
                    setFilterMemberLevel(c.MemberLevel.Internal.value);
                  }}
                >
                  {c.MemberLevel.Internal.label}
                </Radio.Button> */}
              </Radio.Group>
            </Space>,
          );

          if (hasRight('vpngroup_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ]);
          }
          return toolbarDoms;
        }}
        columns={columns}
        params={{
          productIds:
            productId && productId !== c.DefaultOptionAll.key
              ? parseInt(productId)
              : undefined,
          status: filterStatus,
          type: filterType,
          memberLevel: filterMemberLevel,
        }}
        request={loadData}
        rowSelection={{
          // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
          // 注释该行则默认不显示下拉选项
          // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          defaultSelectedRowKeys: [],
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectIds(selectedRowKeys);
          },
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
            <span>
              <a
                onClick={async () => {
                  setBatchChangeProductsVisible(true);
                }}
              >
                关联产品
              </a>
            </span>
          </Space>
        )}
      />
      <Form
        loadGroupId={undefined}
        visible={formVisible}
        current={current}
        parent={parent}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
          setParent(undefined);
        }}
      />
      <BatchChangeProductsForm
        visible={batchChangeProductsVisible}
        onSubmit={handleBatchChangeProductsSubmit}
        onCancel={() => {
          setBatchChangeProductsVisible(false);
        }}
      />
    </PageContainer>
  );
};

export default VpnGroupTreeList;
